package com.study.service2.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
public class ProductServiceSentinel {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate()
    {
        return new RestTemplate();
    }


    @SentinelResource(value = "hi", blockHandler = "selectUserByNameBlockHandler", fallback = "selectUserByNameFallback")
    public String hi(){
        return  restTemplate.getForObject("http://localhost:8081/app/jsontom/hi/", String.class);
    }
    @SentinelResource(value = "hello", blockHandler = "selectUserByNameBlockHandler", fallback = "selectUserByNameFallback")
    public String hello(){
        return  restTemplate.getForObject("http://localhost:8081/app/jsontom/hello/", String.class);
    }

    // 服务流量控制处理，参数最后多一个 BlockException，其余与原函数一致。
    public Object selectUserByNameBlockHandler(String username, BlockException ex)
    {
        System.out.println("selectUserByNameBlockHandler异常信息：" + ex.getMessage());
        return "{\"code\":\"500\",\"msg\": \"" + username + "服务流量控制处理\"}";
    }

    // 服务熔断降级处理，函数签名与原函数一致或加一个 Throwable 类型的参数
    public Object selectUserByNameFallback(String username, Throwable throwable)
    {
        System.out.println("selectUserByNameFallback异常信息：" + throwable.getMessage());
        return "{\"code\":\"500\",\"msg\": \"" + username + "服务熔断降级处理\"}";
    }


}
